<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="filter-container">
        <el-input
            clearable
            v-model="param.jobNumber"
            :style="searchInputStyle"
            class="filter-item"
            placeholder="请输入员工工号"
        ></el-input>
        <el-date-picker
            v-model="dateOptions"
            type="daterange"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions">
        </el-date-picker>
        <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="员工姓名"  prop="userName" align="center" width="120px"/>
      <el-table-column label="员工工号"  prop="jobNumber" align="center" width="120px"/>
      <el-table-column label="员工角色"  prop="role" align="center" width="160px"/>
      <el-table-column label="打卡时间"  prop="createTime" align="center"/>
    </el-table>
   
   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

  </div>
</template>

<script>
import { findUserClockRecord } from '../../api/reClockIn'
export default {
    name: 'reClockIn_list',
    data () {
        return {
            listQuery: {
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            param: {
                jobNumber: '',                              //员工工号
                strTime: '',                           //开始时间
                endTime: '',                          //结束时间
                // status: '',//可不传，是否打卡
            },
            dateOptions: this.getNowTime(),
            searchInputStyle: 'width: 150px;margin-right:15px;',
            total: 0,                                      //数据的总数
            tableInfo: [],
            loadingList: false,
            loading: false,
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    picker.$emit('pick', [start, end]);
                    }
                }]
            },
        }
    },
    methods: {
        getData(){
          this.listQuery.page = 1
          this.listQuery.limit = 10
          this.handleFilter()
        },
        async handleFilter() {
            this.loadingList = true
            let query = Object.assign({},this.listQuery)
            if(this.param.jobNumber){ query.jobNumber = this.param.jobNumber}
            if(this.dateOptions){ query.strTime = this.dateOptions[0],query.endTime = this.dateOptions[1]}
            let data = await findUserClockRecord(query)
            let errmsg = data.msg
            if(data.code == '1'){
                this.total = data.data.count
                this.tableInfo = data.data.list
                this.loadingList = false
                this.tableInfo.forEach(item => {
                      item.role = this.roleName(item.role)
                  });
            } else {
                this.$message({
                message: errmsg,
                type: 'warning'
            })
            }
            this.loadingList = false
        },
        roleName(val){
            return val == '0'?'超级管理员':
                val ==  '1' ?'工艺管理员':
                val == '2'?'员工管理员':
                val == '3'?'QC质量检':
                val == '4'?'计划人员':
                val == '5'?'EC首产检':
                val == '6'?'FC非标检':
                val == '7'?'QE':
                val == '8'?'普通员工':
                val == '9'?'工段长':
                val == '10'?'试水':
                val == '11'?'试水检测':
                val == '12'?'总监':
                val == '14'?'超级管理员':
                val == '15'?'车间主任':
                val == '16'?'PMC':
                val == '19'?'生产':
                val == '23'?'质量文员':
                val == '24'?'质量总监':
                val == '25'?'数控机台调度员':
                val == '26'?'包装工段长权限':
                val == '27'?'工艺经理': '-'
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
          this.listQuery.limit = val
          this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.handleFilter()
        },
        transformDat(res) {
          const mapInfo = {
            index: '序号',
            userName:'员工姓名',
            jobNumber: '员工工号',
            role: '员工角色',
            createTime: '打卡时间'
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          console.log(props)
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          console.log(data)
          return { header, data }
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          query.page = 1
          query.limit = 10000
          if(this.param.jobNumber){ query.jobNumber = this.param.jobNumber}
          if(this.dateOptions){ query.strTime = this.dateOptions[0],query.endTime = this.dateOptions[1]}

          let arr = await findUserClockRecord(query)
          let dateString = this.dateOptions?this.dateOptions[0] + '至' + this.dateOptions[1]:''
          const { header, data } = this.transformDat(this.setSort(arr.data.list))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: dateString+'员工打卡记录excel', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              index: index+1,
              userName: item.userName,
              jobNumber: item.jobNumber,
              role: this.roleName(item.role),
              createTime: item.createTime
            }
            arr1.push(obj)
          })
          return arr1
        },
        //初始默认执行(重点)，返回日期格式YYYY-MM-DD HH:MM:SS
        getNowTime() {
            let dateTime = +new Date()+8*3600*1000
            const start = new Date(dateTime - 3600 * 1000 * 24 * 7)
                .toISOString()
                .replace('T', ' ')
                .split('.')[0] //默认开始时间7天前
            const end = new Date(dateTime)
                .toISOString()
                .replace('T', ' ')
                .split('.')[0]//默认结束时间当前时间
            console.log([start, end])
            return [start, end]
        },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>

</style>